package com.example.lianjuan.ui.frament;

import android.graphics.Rect;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.lianjuan.Base.BaseApplication;
import com.example.lianjuan.Base.BaseFragment;
import com.example.lianjuan.Base.IlinearInfo;
import com.example.lianjuan.Model.domain.SearchResult;
import com.example.lianjuan.Presenter.impl.impl.SearchPresenterImpl;
import com.example.lianjuan.R;
import com.example.lianjuan.Utils.KeyboardUtil;
import com.example.lianjuan.Utils.LogUtils;
import com.example.lianjuan.Utils.PresenterManang;
import com.example.lianjuan.Utils.SizeUtils;
import com.example.lianjuan.Utils.TicketUtil;
import com.example.lianjuan.Utils.ToastUtil;
import com.example.lianjuan.View.ISearchPageCallback;
import com.example.lianjuan.ui.adapter.LinearItemContentAdapter;
import com.example.lianjuan.ui.custom.TextFlowLayout;
import com.lcodecore.tkrefreshlayout.utils.LogUtil;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;

import org.w3c.dom.Text;

import java.util.List;

public class SearchFragment extends BaseFragment implements ISearchPageCallback, TextFlowLayout.onItemFlowClickListener {

    private SearchPresenterImpl mSearchPresenter;
    private LinearLayout mSearchHistoryLayout;
    private LinearLayout mRecommendLayout;
    private TextFlowLayout mRecommend;
    private TextFlowLayout mSearchHistory;
    private ImageView mSearchDelete;
    private RecyclerView mSearchList;
    private LinearItemContentAdapter mAdapter;
    private SmartRefreshLayout mRefresh;
    private ImageView mSearchDeleteBtn;
    private EditText mSearchEdit;
    private TextView mSearchDeleteText;
    private static final String CANCEL = "取消";
    private static final String SEARCH = "搜索";

    @Override
    protected void initView(View view) {
        mSearchHistoryLayout = view.findViewById(R.id.search_history_layout);
        mRecommendLayout = view.findViewById(R.id.recommend_layout);
        mSearchHistory = view.findViewById(R.id.search_history);
        mRecommend = view.findViewById(R.id.recommend);
        mSearchDelete = view.findViewById(R.id.search_delete);
        mSearchList = view.findViewById(R.id.search_page_recycler);
        mRefresh = view.findViewById(R.id.refresh_refreshLayout);
        mSearchDeleteBtn = view.findViewById(R.id.search_delete_btn);
        mSearchEdit = view.findViewById(R.id.search_edit);
        mSearchDeleteText = view.findViewById(R.id.search_Delete_text);
        //刷新头部显示
        mRefresh.setRefreshHeader(new ClassicsHeader(BaseApplication.getContext()));
        mRefresh.setRefreshFooter(new ClassicsFooter(BaseApplication.getContext()));
        //设置recycle布局管理器
        mSearchList.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new LinearItemContentAdapter();
        mSearchList.setAdapter(mAdapter);
        mSearchList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                int i = SizeUtils.dip2px(BaseApplication.getContext(), 5);
                outRect.top = i;
                outRect.bottom = i;
            }
        });
        //不显示搜索界面
        mSearchList.setVisibility(View.GONE);
        setUpState(State.SUCCESS);

    }

    @Override
    public void onSearchSuccess(SearchResult result) {
        //搜索数据返回
        setUpState(State.SUCCESS);
        List<SearchResult.DataDTO.TbkDgMaterialOptionalResponseDTO.ResultListDTO.MapDataDTO> data = result.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data();
        mAdapter.setData(data);
        //数据返回成功，隐藏历史和推荐
        mRecommendLayout.setVisibility(View.GONE);
        mSearchHistoryLayout.setVisibility(View.GONE);
        //显示搜索界面
        mSearchList.setVisibility(View.VISIBLE);
    }

    @Override
    protected void initListener() {
        //自定义控件点击回调
        mSearchHistory.setItemFlowClickListener(this);
        mRecommend.setItemFlowClickListener(this);
        //删除历史后，对历史记录界面隐藏,
        mSearchDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSearchPresenter != null) {
                    //删除数据库里的数据
                    mSearchPresenter.delHistories();
                    mSearchHistoryLayout.setVisibility(View.GONE);
                }
            }
        });
        //商品点击回调
        mAdapter.setOnItemClickListener(new LinearItemContentAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(IlinearInfo result) {
                TicketUtil.toTickerPager(getContext(), result);
            }
        });
        //禁止下拉
        mRefresh.setEnableRefresh(false);
        mRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mSearchPresenter.loaderMore();
            }
        });
        //网络错误点击重新加载
        networkClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSearchPresenter != null) {
                    mSearchPresenter.research();
                }
            }
        });
        //搜索监听
        mSearchEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //当actionId等于搜索代码时,进行搜索操作
                if (mSearchPresenter != null && actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String keyWork = v.getText().toString().trim();
                    //拿到的数据是否为空
                    if (TextUtils.isEmpty(keyWork)) {
                        return false;
                    }
                    mSearchPresenter.doSearch(keyWork);
                }
                return false;
            }
        });
        mSearchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                boolean hasText = s.toString().isEmpty();
                //输入框内容是否为空，隐藏或显示删除按钮
                mSearchDeleteBtn.setVisibility(!hasText ? View.VISIBLE : View.GONE);
                mSearchDeleteText.setText(!hasText ? SEARCH : CANCEL);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //删除输入框里的数据
        mSearchDeleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSearchEdit.setText("");
            }
        });
        //手动取消和手动搜索按钮
        mSearchDeleteText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //text内容等于搜索时发起搜索
                if (SEARCH.contentEquals(mSearchDeleteText.getText())) {
                    mSearchPresenter.doSearch(mSearchEdit.getText().toString());
                    //发起搜索后隐藏键盘
                    KeyboardUtil.hide(BaseApplication.getContext(), v);
                }
                //text内容等于取消时,隐藏商品界面,当历史数据不为0，显示历史数据和推荐
                if (CANCEL.contentEquals(mSearchDeleteText.getText())) {
                    //隐藏键盘
                    KeyboardUtil.hide(BaseApplication.getContext(), v);
                    //直接获取搜索历史
                    mSearchPresenter.getHistories();
                    //mSearchHistoryLayout.setVisibility(mSearchHistory.getHistorySize() > 0 ? View.VISIBLE : View.GONE);
                    mRecommendLayout.setVisibility(mRecommend.getHistorySize() > 0 ? View.VISIBLE : View.GONE);
                    mSearchList.setVisibility(View.GONE);

                }
            }
        });
    }

    @Override
    protected void onNetworkClick() {
        super.onNetworkClick();
    }

    @Override
    protected void initPresenter() {
        mSearchPresenter = PresenterManang.getInstance().getSearchPresenter();
        mSearchPresenter.registerViewCallback(this);
    }

    @Override
    protected void loadData() {
        //获取推荐
        mSearchPresenter.getRecommendWords();
        //获取历史记录
        mSearchPresenter.getHistories();
    }

    @Override
    protected void release() {
        mSearchPresenter.unregisterViewCallback(this);
    }

    @Override
    protected View loadRootView(LayoutInflater inflater, @Nullable ViewGroup container) {
        return inflater.inflate(R.layout.fragment_search_bar_layout, container, false);
    }

    @Override
    protected int getRootViewResID() {
        return R.layout.fragment_search_layout;
    }

    @Override
    public void onNetworkError() {
        setUpState(State.ERROR);
    }

    @Override
    public void onLoadEmpty() {
        setUpState(State.EMPTY);
    }

    @Override
    public void onLoadNone() {
    }

    @Override
    public void onLoadLoading() {
        setUpState(State.LOADING);
    }

    @Override
    public void onLoadError() {
        setUpState(State.ERROR);
    }

    @Override
    public void onHistoriesLoaded(List<String> histories) {
        LogUtils.d(this, "histories---->" + histories.size());
        mSearchHistory.setTextList(histories);
        mSearchHistoryLayout.setVisibility(View.VISIBLE);
    }

    @Override
    public void onHistoriesDeleted() {

    }

    @Override
    public void onLoadedMord(SearchResult result) {
        List<SearchResult.DataDTO.TbkDgMaterialOptionalResponseDTO.ResultListDTO.MapDataDTO> map_data = result.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data();
        //结束刷新
        mRefresh.finishLoadMore();
        ToastUtil.showToast("新增" + map_data.size() + "条内容");
        if (map_data != null) {
            mAdapter.addMoreData(map_data);
        }
    }

    @Override
    public void onLoadedMordError() {
        //结束刷新
        mRefresh.finishLoadMore();
        ToastUtil.showToast("没有更多内容");
    }

    @Override
    public void onLoadedMordEmpty() {
        //结束刷新
        mRefresh.finishLoadMore();
        ToastUtil.showToast("没有更多内容");
    }

    @Override
    public void onRecommendWordLoaded(List<String> histories) {
        int size = histories.size();
        //推荐数据
        if (histories != null || size > 0) {
            mRecommend.setTextList(histories);
            mRecommendLayout.setVisibility(View.VISIBLE);
            //对搜索历史layout先隐藏，如果有数据会调用onHistoriesLoaded方法，再进行显示
            mSearchHistoryLayout.setVisibility(View.GONE);
        } else {
            mRecommendLayout.setVisibility(View.GONE);
            //对搜索历史layout先隐藏，如果有数据会调用onHistoriesLoaded方法，再进行显示
            mSearchHistoryLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void onError() {
        setUpState(State.ERROR);
    }

    @Override
    public void onItemFlowClick(String text) {
        doSearch(text);
    }

    /**
     * 发起搜索和Edit控件写入搜索内容
     *
     * @param text
     */
    private void doSearch(String text) {
        if (mSearchPresenter != null) {
            mSearchList.scrollToPosition(0);
            mSearchEdit.setText(text);
            //获得焦点
            mSearchEdit.requestFocus();
            //把光标放到最后
            mSearchEdit.setSelection(text.length());
            mSearchPresenter.doSearch(text);
            boolean focusable = mSearchEdit.hasFocusable();
        }
    }
}
